﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.Log;

namespace Common.Http.WebApi
{
    public class HttpApiIdentity : HttpApiClient
    {
        public HttpApiIdentity(string baseAddress)
            : base(baseAddress)
        {

        }


        protected override async Task<bool> DoRequestAgain(System.Net.Http.HttpResponseMessage response)
        {
            //授权失效重新登录
            if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                await Login();
                return true;
            }
            return false;
        }

        /// <summary>
        /// 内置账号
        /// </summary>
        public Models.Acount LoginUser { get; set; }

        /// <summary>
        /// 登录
        /// </summary>
        public virtual async Task Login()
        {
            if (LoginUser == null)
            {
                throw new ArgumentNullException("接口调用异常：LoginUser is null");
            }
            var token = await GetToken(LoginUser.UserName, LoginUser.Password);
            DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
        }

        /// <summary>
        /// 获取token地址
        /// </summary>
        protected string tokenUrl = @"token";

        /// <summary>
        /// 帐号注册地址
        /// </summary>
        protected string regUrl = @"api/Account/Register";

        /// <summary>
        /// 获取登录token
        /// </summary>
        /// <param name="user"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        protected virtual async Task<string> GetToken(string user, string pwd)
        {
            var i = 0;
        getToken:
            var ret = await DoPostAsync<Dictionary<string, string>>(tokenUrl, new Dictionary<string, string>
            {
                {"grant_type","password"},
                {"UserName",user},
                {"password",pwd}
            });
            if (ret != null && ret.ContainsKey("access_token"))
            {
                var token = ret["access_token"];
                return token;
            }
            else
            {
                //call token more
                if (i > 2)
                {
                    throw new FormatException(string.Format("{0}获取token失败,u{2}p{3}.数据:{1}", tokenUrl, Newtonsoft.Json.JsonConvert.SerializeObject(ret), user, pwd));
                }
                i++;
                goto getToken;
            }
        }

        /// <summary>
        /// 注册帐号
        /// </summary>
        /// <param name="user"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public virtual async Task<bool> Register(string user, string pwd)
        {
            var ret = await DoPostAsync(regUrl, new Dictionary<string, string>
            {
                {"UserName" , user},
                {"Password", pwd},
                {"ConfirmPassword",  pwd}
            });
            return ret != null;
        }


    }
}
